package com.dcbeida.activity.sales;

import android.app.ActionBar;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dcbeida.MyApplication;
import com.dcbeida.R;
import com.dcbeida.activity.BaseActivity;
import com.dcbeida.activity.CaptureActivity;
import com.dcbeida.activity.CommonListActivity;
import com.dcbeida.activity.addnewpatient.AddNewPatientAct;
import com.dcbeida.activity.hospital.HospitalActivity;
import com.dcbeida.activity.sign.SignQrCodeActivity;
import com.dcbeida.adapter.ListPopupWindowAdapter;
import com.dcbeida.adapter.StoreAdapter;
import com.dcbeida.bean.CardEnum;
import com.dcbeida.bean.DrugInfo;
import com.dcbeida.bean.HospitalBean;
import com.dcbeida.bean.Image;
import com.dcbeida.bean.MyClientBean;
import com.dcbeida.bean.Patient;
import com.dcbeida.bean.SignStatusEnum;
import com.dcbeida.callback.PhotoCallBack;
import com.dcbeida.listern.DialogCarmerListener;
import com.dcbeida.listern.DialogListener;
import com.dcbeida.mine.PatientListActivity;
import com.dcbeida.utils.CameraUtil;
import com.dcbeida.utils.Constants;
import com.dcbeida.utils.DialogUtils;
import com.dcbeida.utils.GetPhotoFromAlbum;
import com.dcbeida.utils.GifSizeFilter;
import com.dcbeida.utils.GsonUtil;
import com.dcbeida.utils.PutAliyObject;
import com.dcbeida.utils.Utils;
import com.dcbeida.utils.permission.AndPermission;
import com.dcbeida.utils.permission.PermissionListener;
import com.dcbeida.utils.permission.Rationale;
import com.dcbeida.utils.permission.RationaleListener;
import com.dcbeida.widget.PhotoViewShow;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.SelectionCreator;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.w3c.dom.Text;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.dcbeida.utils.Constants.PERMISSION_CAMERA;
import static com.dcbeida.utils.Constants.PERMISSION_WRITE_EXTERNAL_STORAGE;
import static com.dcbeida.utils.Constants.REQUEST_CODE_CHOOSE;
import static com.dcbeida.utils.Constants.REQUEST_CODE_CHOOSE_CF;
import static com.dcbeida.utils.Constants.REQUEST_PATIENT_CODE;

/**
 * 门店销售
 * Created by fancl on 2016/8/8.
 */
public class StoresalesActivity extends BaseActivity implements StoresalesContract.View, View.OnClickListener {


    @Bind(R.id.img_back)
    ImageView img_back;

    @Bind(R.id.lin_tel)
    LinearLayout lin_tel;
    @Bind(R.id.lin_ss_head)
    LinearLayout lin_ss_head;


    @Bind(R.id.lin_name)
    LinearLayout lin_name;


    @Bind(R.id.lin_yp)
    LinearLayout lin_yp;


    @Bind(R.id.et_tel)
    EditText et_tel;

    @Bind(R.id.tv_ss)
    TextView tv_ss;

    @Bind(R.id.tv_ss2)
    TextView tv_ss2;

    @Bind(R.id.tv_ss3)
    TextView tv_ss3;
    @Bind(R.id.iv_ss3)
    ImageView iv_ss3;


    @Bind(R.id.et_name)
    EditText et_name;
    @Bind(R.id.et_price)
    EditText et_price;


    @Bind(R.id.et_idcard)
    EditText et_idcard;

    @Bind(R.id.tv_yp)
    TextView tv_yp;

    @Bind(R.id.et_count)
    EditText et_count;

    @Bind(R.id.img_fp)
    ImageView img_fp;

    @Bind(R.id.lin_fp)
    LinearLayout lin_fp;

    @Bind(R.id.img_cf)
    ImageView img_cf;
    @Bind(R.id.lin_cf)
    LinearLayout lin_cf;


    @Bind(R.id.tv_type)
    TextView tv_type;

    @Bind(R.id.tv_all2)
    TextView tv_all2;

    @Bind(R.id.lin_add)
    LinearLayout lin_add;

    @Bind(R.id.lin_confim)
    LinearLayout lin_confim;

    @Bind(R.id.lin_id)
    LinearLayout lin_id;
    @Bind(R.id.tv_search)
    TextView tv_search;

    @Bind(R.id.et_name_with_tel)
    EditText et_name_with_tel;

    @Bind(R.id.iv_ss_saoma)
    ImageView iv_ss_saoma;


    @Bind(R.id.tv_confim)
    TextView tv_confim;

    @Bind(R.id.ll_credit_type)
    LinearLayout ll_credit_type;
    @Bind(R.id.tv_crdeit_type)
    TextView tv_crdeit_type;
    @Bind(R.id.ll_tel_type)
    LinearLayout ll_tel_type;
    @Bind(R.id.tv_tel_type)
    TextView tv_tel_type;

    @Bind(R.id.tv_sign_status)
    TextView tv_sign_status;


    @Bind(R.id.ll_yymc)
    LinearLayout ll_yymc;
    @Bind(R.id.tv_yymc)
    TextView tv_yymc;

    @Bind(R.id.tvAddCode)
    TextView tvAddCode;
    @Bind(R.id.et_jzys)
    EditText et_jzys;//就诊医生

    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;

    @Bind(R.id.recyclerview2)
    RecyclerView chuFangview;

    private StoreAdapter storeAdapter;

    private StoreAdapter chuFangAdapter;

    private static final String[] requestPermissions = {
            PERMISSION_CAMERA,
            PERMISSION_WRITE_EXTERNAL_STORAGE
    };
    private List<String> obtainPathResult;//本地图片地址

    private List<String>chuFangPathResult;//

    private ArrayList<String> imgUrl;//服务器图片地址

    private ArrayList<String> chuFangImgUrl;//服务器图片地址


    private ListPopupWindow mListPopupWindow;
    private ListPopupWindowAdapter mListPopupWindowAdapter;


    private StoresalesContract.Present mPresent;

    LayoutInflater inflater;

    private String code;

    private int type = 0;

    public Handler iHandler;

    private String localUrl = "";//选取的本地图片url
    private String cfurl = "";//处方url
    private String fpurl = "";//发票url
    private HospitalBean hospitalBean;
    private int hospitalid = 0;//0表示不传

    int icon = 0;//1表示我正在上传发票，2表示我正在上传处方

    String tempName = "";//上次做的搜索内容
    private ProgressDialog dialog;

    private int creditType=0;//默认0

    private int telType = 0;


    private Patient patient;


    private int currentClickType=REQUEST_CODE_CHOOSE;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_storesales;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflater = LayoutInflater.from(this);
        initParams();
        initPopupWindow();
        initListern();
        addMessageHandler();


    }

    private void initListern() {
        tv_ss.setOnClickListener(this);
        tv_ss2.setOnClickListener(this);
        iv_ss3.setOnClickListener(this);
        tv_ss3.setOnClickListener(this);
        lin_yp.setOnClickListener(this);
        img_back.setOnClickListener(this);
        lin_confim.setOnClickListener(this);
        lin_fp.setOnClickListener(this);
        lin_cf.setOnClickListener(this);
        tv_confim.setOnClickListener(this);
        ll_yymc.setOnClickListener(this);
        tv_search.setOnClickListener(this);
        iv_ss_saoma.setOnClickListener(this);
        ll_credit_type.setOnClickListener(this);
        ll_tel_type.setOnClickListener(this);
    }

    private void initPopupWindow() {
        mListPopupWindow = new ListPopupWindow(mContext);
        mListPopupWindow.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        mListPopupWindow.setHeight(ActionBar.LayoutParams.WRAP_CONTENT);
        mListPopupWindowAdapter = new ListPopupWindowAdapter(mContext);
        mListPopupWindow.setAdapter(mListPopupWindowAdapter);
        mListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("info", "position=" + position);
                Patient patient = (Patient) mListPopupWindowAdapter.getItem(position);
                et_tel.setText(patient.getPhonenum());
                et_idcard.setText(patient.getIdcardnum());
                et_name.setText(patient.getTruename());
                tv_yymc.setText(patient.getHospitalname());
                hospitalid = patient.getHospitalid();


                mListPopupWindow.dismiss();
                et_price.requestFocus();
                et_price.setFocusable(true);
                et_price.setFocusableInTouchMode(true);
            }
        });

        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (et_name.getText().toString().trim().length() < 2) {
//                    return;
//                }
//                //文字变动 ， 有未发出的搜索请求，应取消
//                if (mHandler.hasMessages(MSG_SEARCH)) {
//                    mHandler.removeMessages(MSG_SEARCH);
//                }
//                //如果为空 直接显示搜索历史
//                if (!TextUtils.isEmpty(s)) {
//                    //否则延迟800ms开始搜索
//                    mHandler.sendEmptyMessageDelayed(MSG_SEARCH, 2000); //自动搜索功能
//                }

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //搜索请求

            type = 2;
            if (tempName.equals(getName())) {
                tempName = "";
                return;
            }
            if (mListPopupWindow != null)
                mListPopupWindow.dismiss();
            tempName = getName();
            mListPopupWindowAdapter.setType(type);
            mPresent.getPatientInfo(3, getName());

        }

    };
    private static final int MSG_SEARCH = 1;

    @Override
    public String getEditTel() {
        return et_tel.getText().toString();
    }

    @Override
    public String getPatinenId() {
        return et_idcard.getText().toString();
    }

    @Override
    public String getName() {
        return et_name.getText().toString();
    }

    @Override
    public void showTelTip(String msg) {
        if (msg.equalsIgnoreCase("ok")) {

            showTip(getString(R.string.sccg));
        } else {
            showTip(msg);
        }
    }


    @Override
    public void showPatientlist(ArrayList<Patient> patients) {
        if (type == 1) {
            if (patients != null && patients.size() > 0) {
                Patient obj = patients.get(0);
                if (!getName().equals(obj.getTruename())) {
                    //提示患者信息不对
                    String errorTip = getString(R.string.str116, obj.getTruename());
                    DialogUtils.showDialogTip(StoresalesActivity.this, R.string.str115, errorTip, new DialogListener() {
                        @Override
                        public void onCancl(Dialog dialog) {
                            dialog.cancel();
                        }

                        @Override
                        public void onConfirm(Dialog dialog) {//执行提交
                            mPresent.adddrugsales(et_name.getText().toString().trim(),
                                    et_idcard.getText().toString().trim(),
                                    et_tel.getText().toString().trim(),
                                    Utils.dFormat(Double.parseDouble(et_price.getText().toString().trim())),
                                    fpurl,cfurl, et_jzys.getText().toString().trim(),
                                    hospitalid,creditType);
                            dialog.cancel();
                        }
                    }, R.string.cancel, R.string.confirm);
                    return;
                }
            }
            showSubmit();//执行提交确认
        } else {

            mListPopupWindowAdapter.setmArrayList(patients);
            if (type == 0) {
                mListPopupWindow.setAnchorView(lin_tel);
            } else if (type == 1) {
                mListPopupWindow.setAnchorView(lin_id);
            } else if (type == 2) {
                mListPopupWindow.setAnchorView(lin_name);
            } else if (type == 4 || type == 5) {
                mListPopupWindow.setAnchorView(lin_ss_head);
            } else {
                mListPopupWindow.setAnchorView(lin_name);
            }
            mListPopupWindow.show();

        }

    }

    @Override
    public void showPatient(Patient patient) {
        this.patient = patient;
        et_tel.setText(patient.getPhonenum());
        et_idcard.setText(patient.getIdcardnum());
        et_name.setText(patient.getTruename());
        tv_yymc.setText(patient.getHospitalname());
        hospitalid = patient.getHospitalid();
        String cardName = CardEnum.getCardName(patient.getCardtype());
        tv_crdeit_type.setText(cardName);
        creditType = patient.getCardtype();
        if(patient.getPhonenum() != null && patient.getPhonenum().contains("-")){
            telType =1;
            tv_tel_type.setText("固定电话");
        }else{
            tv_tel_type.setText("手机号");
        }
        SignStatusEnum anEnum = SignStatusEnum.getEnum(patient.getSignstatus());
        tv_sign_status.setText(anEnum.getName());
        tv_sign_status.setTextColor(getResources().getColor(anEnum.getColor()));
    }

    @Override
    public void showP() {

    }

    @Override
    public void setPresenter(StoresalesContract.Present presenter) {

    }

    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
            rationale.resume();
        }
    };

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantPermissions) {
            SelectionCreator result =  Matisse.from(mContext)
                    .choose(MimeType.ofAll(), false)
                    .countable(true)
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, "com.dcbeida.utils.GifSizeFilter"))
                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideEngine());
            if(currentClickType == REQUEST_CODE_CHOOSE){
                result.maxSelectable(Constants.MAX_IMAGE_SIZE - imgUrl.size());
            }else{
                result.maxSelectable(Constants.MAX_IMAGE_SIZE - chuFangImgUrl.size());
            }
            result.forResult(currentClickType);
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {

        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_search:
                if (TextUtils.isEmpty(et_name_with_tel.getText())) {
                    showTip("请输入患者姓名或者手机号");
                    return;
                }
                String et_value = et_name_with_tel.getText().toString().trim();
                Pattern p = Pattern.compile("[0-9]*");
                Matcher m = p.matcher(et_value);
                if (m.matches()) {
                    //输入的是手机号码
                    if (et_name_with_tel.getText().length() == 11) {
                        type = 4;//设置不一样
                    } else {
                        showTip("输入的手机号码不正确");
                        return;
                    }

                } else {
                    type = 5;//设置不一样
                }

//                if (type == 4) {
//                    mPresent.getPatientInfo(1, et_name_with_tel.getText().toString().trim());
//                } else if (type == 5) {
//                    mPresent.getPatientInfo(3, et_name_with_tel.getText().toString().trim());
//                }

                Bundle b = new Bundle();
                if(type == 4){
                    b.putInt("searchType", 1);
                }else if(type == 5){
                    b.putInt("searchType", 3);
                }
                b.putString("keyWord", et_name_with_tel.getText().toString().trim());
                showActivityForResult(PatientListActivity.class, b, Constants.REQUEST_PATIENT_CODE);

                break;
            case R.id.iv_ss_saoma://
                b = new Bundle();
                b.putInt("type", CaptureActivity.TYPE_PAT);
                b.putString("title","患者查询");
                showActivityForResult(CaptureActivity.class, b, Constants.RESULT_CAPTER_WITH_PAT);
                break;
            case R.id.img_back:
                finish();
                break;

            case R.id.tv_ss://搜索信息(手机号码)
                type = 0;
                if (TextUtils.isEmpty(getEditTel())) {
                    showTelTip("请输入手机号码！");
                    return;
                }
                mListPopupWindowAdapter.setType(type);
                mPresent.getPatientInfo(1, getEditTel());
                break;

            case R.id.tv_ss2://搜索信息(身份证号码)
                type = 1;
                //                if (TextUtils.isEmpty(getPatinenId())) {
                //                    showTelTip("请输入身份证号码！");
                //                    return;
                //                }
                mListPopupWindowAdapter.setType(type);
                mPresent.getPatientInfo(2, getPatinenId());
                break;

            case R.id.iv_ss3://搜索信息(名字)
                type = 2;
                if (TextUtils.isEmpty(getName())) {
                    showTelTip("请输入姓名！");
                    return;
                }
//                if (mListPopupWindow != null)
//                    mListPopupWindow.dismiss();
//                tempName = getName();
//                mListPopupWindowAdapter.setType(type);
//                mPresent.getPatientInfo(3, getName());
                b = new Bundle();
                b.putInt("searchType", 3);
                b.putString("keyWord", getName());
                showActivityForResult(PatientListActivity.class, b, Constants.REQUEST_PATIENT_CODE);
                break;

            case R.id.lin_confim:
                b = new Bundle();
                b.putInt("type", CaptureActivity.TYPE_RE);
                b.putString("title", "条形码扫描");
                showActivityForResult(CaptureActivity.class, b, Constants.RESULT_CAPTER);
                break;
            case R.id.ll_credit_type:
                b = new Bundle();
                b.putInt("type", 0);
                showActivityForResult(CommonListActivity.class, b, Constants.RESULT_CRIDET_TYPE);
                break;
            case R.id.ll_tel_type:
                b = new Bundle();
                b.putInt("type", 1);
                showActivityForResult(CommonListActivity.class, b, Constants.RESULT_TEL_TYPE);
                break;

            case R.id.lin_fp:
                icon = 1;
                //                DialogUtils.showDialog(StoresalesActivity.this, new DialogCarmerListener() {
                //                    @Override
                //                    public void onAlbum() {
                //                        GetPhotoFromAlbum.ChooseWay(StoresalesActivity.this,
                //                                CameraUtil.PHOTO_PICKED_WITH_DATA);
                //                    }
                //
                //                    @Override
                //                    public void onPhotograph() {
                //
                //                        GetPhotoFromAlbum.ChooseWay(StoresalesActivity.this,
                //                                CameraUtil.CAMERA_WITH_DATA);
                //                    }
                //                });

                //权限申请
                AndPermission.with(mContext)
                        .requestCode(100)
                        .permission(requestPermissions)
                        .rationale(rationaleListener)
                        .send();


                break;
            case R.id.lin_cf:
                icon = 2;
                DialogUtils.showDialog(StoresalesActivity.this, new DialogCarmerListener() {
                    @Override
                    public void onAlbum() {
                        GetPhotoFromAlbum.ChooseWay(StoresalesActivity.this,
                                CameraUtil.PHOTO_PICKED_WITH_DATA);
                    }

                    @Override
                    public void onPhotograph() {

                        GetPhotoFromAlbum.ChooseWay(StoresalesActivity.this,
                                CameraUtil.CAMERA_WITH_DATA);
                    }
                });
                break;
            case R.id.tv_confim:
                if (TextUtils.isEmpty(et_name.getText())) {
                    showTelTip("请填写患者姓名");
                    return;
                }



                if(patient != null && patient.getCardtype() ==CardEnum.ZRXLHZ.getType()){

                }else {

                    if (TextUtils.isEmpty(et_tel.getText())) {
                        showTelTip("请填写患者联系方式");
                        return;
                    }

                    if (telType == 0 && et_tel.getText().toString().length() !=11) {
                        showTelTip("请正确填写患者手机号码");
                        return;
                    }

                    if (telType == 1 && !et_tel.getText().toString().contains("-")) {
                        showTelTip("请正确填写患者固定电话");
                        return;
                    }

                    if (TextUtils.isEmpty(et_idcard.getText())) {
                        showTelTip("请填写患者证件号");
                        return;
                    }
                }

                if(patient == null){
                    //addNewPatient();
                    //mPresent.getPatientInfo2();
                    mPresent.getPatientInfo(2, getPatinenId(),1);
                    return;
                }


                if (TextUtils.isEmpty(et_price.getText())) {
                    showTelTip("请填写金额");
                    return;
                }

//                if (TextUtils.isEmpty(et_price.getText().toString()) || Double.parseDouble(et_price.getText().toString().trim()) == 0) {
//                    showTelTip("请填写金额");
//                    return;
//                }

                if (!mPresent.isDrugInfoList()) {
                    showTelTip("请扫码");
                    return;
                }

                if (creditType == 0 && getPatinenId().length() != 18) {
                    showTelTip("请填写正确的身份证");
                    return;
                }

                if(chuFangImgUrl.size() == 0){
                    showTelTip("请上传处方");
                    return;
                }

                showSubmit();
                //                if (TextUtils.isEmpty(getPatinenId())) {
                //                    type = -1;
                //                    showSubmit();
                //                }
                //                else{
                //                    type = 1;
                //                    mPresent.getPatientInfo(2, getPatinenId());
                //                }


                break;


            case R.id.ll_yymc:
                b = new Bundle();
                showActivityForResult(HospitalActivity.class, b, Constants.HOSPITAL_TYPE);
                break;

        }
    }

    private void showSubmit() {
        int mesTip = 0;
        fpurl = "";
        if (imgUrl.size() == 0) {
            mesTip = R.string.str117;
        } else {
            mesTip = R.string.message;
        }

        for (int i = 0; i < imgUrl.size(); i++) {
            if (i != 0 && i != imgUrl.size()) {
                fpurl += "," + imgUrl.get(i);
            } else {
                fpurl += imgUrl.get(i);
            }
        }

        cfurl ="";
        for (int i = 0; i < chuFangImgUrl.size(); i++) {
            if (i != 0 && i != chuFangImgUrl.size()) {
                cfurl += "," + chuFangImgUrl.get(i);
            } else {
                cfurl += chuFangImgUrl.get(i);
            }
        }

        new AlertDialog.Builder(this).setMessage(mesTip)
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton(R.string.confim, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if(SignStatusEnum.WQ.getType() == patient.getSignstatus()){
                    Bundle bundle = new Bundle();
                    bundle.putInt("patientId",patient.getId());
                    bundle.putInt("type",1);
                    showActivityForResult(SignQrCodeActivity.class,bundle,Constants.REQUEST_ADD_PATIENT_SIGN);
                }else {
                    mPresent.adddrugsales(et_name.getText().toString().trim(),
                            et_idcard.getText().toString().trim(),
                            et_tel.getText().toString().trim(),
                            Utils.dFormat(Double.parseDouble(et_price.getText().toString().trim())),
                            fpurl, cfurl, et_jzys.getText().toString().trim(),
                            hospitalid, creditType);
                }
            }
        }).show();
    }

    private void initParams() {
        mPresent = new StoresalesPresenter(this, this);

        obtainPathResult = new ArrayList<String>();
        imgUrl = new ArrayList<String>();

        chuFangPathResult= new ArrayList<String>();
        chuFangImgUrl= new ArrayList<String>();

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerview.setLayoutManager(layoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        recyclerview.setHasFixedSize(true);
        storeAdapter = new StoreAdapter(mContext);
        recyclerview.setAdapter(storeAdapter);
        storeAdapter.setDefaultDrawable(R.drawable.shangchuanfap);
        storeAdapter.setOnItemClickListener(new StoreAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == storeAdapter.mUris.size()) {
                    currentClickType = REQUEST_CODE_CHOOSE;
                    //权限申请
                    AndPermission.with(mContext)
                            .requestCode(100)
                            .permission(requestPermissions)
                            .rationale(rationaleListener)
                            .send();
                } else {
                    //传递当前点击的图片的位置、图片路径集合
                    Bundle bundle = new Bundle();
                    bundle.putInt("position", position);
                    bundle.putStringArrayList("mImages", imgUrl);
                    showActivity(PhotoViewShow.class, bundle);
                }
            }

        });

        storeAdapter.setOnItemDelClickListener(new StoreAdapter.OnRecyclerViewItemDelClickListener() {
            @Override
            public void onItemDelClick(View view, int position) {
                obtainPathResult.remove(position);
                imgUrl.remove(position);
                storeAdapter.setData(imgUrl);
            }
        });

        LinearLayoutManager chuFanglayoutManager = new LinearLayoutManager(mContext);
        chuFanglayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        chuFangview.setLayoutManager(chuFanglayoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        chuFangview.setHasFixedSize(true);
        chuFangAdapter = new StoreAdapter(mContext);
        chuFangview.setAdapter(chuFangAdapter);
        chuFangAdapter.setDefaultDrawable(R.drawable.shangchuanchufang);
        chuFangAdapter.setOnItemClickListener(new StoreAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == chuFangAdapter.mUris.size()) {
                    //权限申请
                    currentClickType = REQUEST_CODE_CHOOSE_CF;
                    AndPermission.with(mContext)
                            .requestCode(100)
                            .permission(requestPermissions)
                            .rationale(rationaleListener)
                            .send();
                } else {
                    //传递当前点击的图片的位置、图片路径集合
                    Bundle bundle = new Bundle();
                    bundle.putInt("position", position);
                    bundle.putStringArrayList("mImages", chuFangImgUrl);
                    showActivity(PhotoViewShow.class, bundle);
                }
            }

        });

        chuFangAdapter.setOnItemDelClickListener(new StoreAdapter.OnRecyclerViewItemDelClickListener() {
            @Override
            public void onItemDelClick(View view, int position) {
                chuFangPathResult.remove(position);
                chuFangImgUrl.remove(position);
                chuFangAdapter.setData(chuFangImgUrl);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(StoresalesActivity.class.getName(), "#########requestCode:" + requestCode + ";######resultCode:" + resultCode);
        if (resultCode == RESULT_OK && requestCode == Constants.RESULT_CAPTER) {//扫码返回
            code = data.getStringExtra("code");
            Log.i(StoresalesActivity.class.getName(), "---" + code);
            mPresent.getdrugcodeinfo(code);

        } else if (resultCode == RESULT_OK && requestCode == Constants.RESULT_CRIDET_TYPE){
            String key = data.getStringExtra("key");
            tv_crdeit_type.setText(key);
            creditType = data.getIntExtra("value",0);
        }else if(resultCode == RESULT_OK && requestCode == Constants.RESULT_TEL_TYPE){
            String key = data.getStringExtra("key");
            tv_tel_type.setText(key);
            telType = data.getIntExtra("value",0);
        }


        else if (resultCode == RESULT_OK && requestCode == Constants.RESULT_CAPTER_WITH_PAT) {//扫码返回用户
            code = data.getStringExtra("code");
            Log.i(StoresalesActivity.class.getName(), "---" + code);
            if (!TextUtils.isEmpty(code) && code.contains("patientId")) {
                Uri uri = Uri.parse(code);
                String patientId = uri.getQueryParameter("patientId");
                type = 4;
                mPresent.getPatientInfo(4, patientId);
            } else if (!TextUtils.isEmpty(code)) {
                type = 4;
                mPresent.getPatientInfo(4, code);
            }

        } else if ((requestCode == CameraUtil.PHOTO_PICKED_WITH_DATA ||
                requestCode == CameraUtil.CAMERA_WITH_DATA ||
                requestCode == CameraUtil.CAMERA_COMPLETE) && resultCode == RESULT_OK) {//获取照片

            GetPhotoFromAlbum.GetPhoto(StoresalesActivity.this, requestCode, data, false, mPhotoCallBack);

        } else if (requestCode == Constants.HOSPITAL_TYPE && resultCode == RESULT_OK) {//选择医院
            Bundle bundle = data.getExtras();
            if (null != bundle) {
                if (bundle.containsKey("hospitalBean")) {
                    hospitalBean = (HospitalBean) bundle.getSerializable("hospitalBean");
                    tv_yymc.setText(hospitalBean.getHospitalname());
                    hospitalid = hospitalBean.getHospitalid();
                }
            }

        } else if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            obtainPathResult.addAll(Matisse.obtainPathResult(data));

            updateImg(Matisse.obtainPathResult(data));

        }

        else if (requestCode == REQUEST_CODE_CHOOSE_CF && resultCode == RESULT_OK) {
            chuFangPathResult.addAll(Matisse.obtainPathResult(data));
            updateImg(Matisse.obtainPathResult(data));

        }else if(requestCode == REQUEST_PATIENT_CODE && resultCode == RESULT_OK){
            Patient patient = (Patient) data.getSerializableExtra("patient");
            Log.i("info", "position=" + GsonUtil.GsonString(patient));
            showPatient(patient);
        }else  if(requestCode == Constants.REQUEST_ADD_PATIENT && resultCode == RESULT_OK){
            int patientId = data.getIntExtra("patientId", 0);
            mPresent.getPatientInfo2(4, patientId+"");
        }else  if(requestCode == Constants.REQUEST_ADD_PATIENT_SIGN && resultCode == RESULT_OK){
            int signstatus = data.getIntExtra("status",0);
            if(signstatus == SignStatusEnum.YQ.getType() || signstatus == SignStatusEnum.JQ.getType() || signstatus == SignStatusEnum.WQ.getType()){
                mPresent.getPatientInfo2(4, patient.getId()+"");
            }else if(signstatus == 99){
                mPresent.adddrugsales(et_name.getText().toString().trim(),
                        et_idcard.getText().toString().trim(),
                        et_tel.getText().toString().trim(),
                        Utils.dFormat(Double.parseDouble(et_price.getText().toString().trim())),
                        fpurl, cfurl, et_jzys.getText().toString().trim(),
                        hospitalid, creditType);
            }
        }
    }

    private void updateImg(List<String> obtainPathResult) {
        dialog = new ProgressDialog(mContext, R.style.myDialogTheme);
        dialog.show();
        View layout = View.inflate(mContext, R.layout.progress, null);
        TextView tv_tip = (TextView) layout.findViewById(R.id.tv_tip);
        tv_tip.setText(R.string.zzsc);
        dialog.setContentView(layout);
        Window win = dialog.getWindow();
        win.setGravity(Gravity.CENTER);
        // 弹出对话框时，底部窗体，不变暗。
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = (int) (MyApplication.widthPixels * 0.85);
        win.setAttributes(lp);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    if (null != dialog) {
                        dialog.dismiss();
                        return true;
                    }
                }
                return false;
            }
        });

        GetPhotoFromAlbum.compressImageByQualityList(obtainPathResult, mContext, iHandler);
    }


    @Override
    public void addItem(DrugInfo info) {
        View view = inflater.inflate(R.layout.activity_inventory_item, null);
        TextView tv_name_numb = ButterKnife.findById(view, R.id.tv_name_numb);
        TextView tv_itemAll = ButterKnife.findById(view, R.id.tv_itemAll);
        tv_name_numb.setText(getString(R.string.name_numb, info.getDrugname(), info.getDrugcode()));
        tv_itemAll.setText(info.getQuantity() + "");
        lin_add.addView(view);
    }

    @Override
    public void setQuantity(int count, int quantity) {
        if (quantity > 0) {
            tvAddCode.setText(R.string.again222);
        } else {
            tvAddCode.setText(R.string.again2);
        }

        tv_type.setText(count + "");
        tv_all2.setText(quantity + "");
    }

    @Override
    public void confimSuccess() {
        sendBroadcast(new Intent(Constants.RECEIVER_SALE_FRESH));
        finish();
    }

    @Override
    public void showAddNewPatient() {
        //根据患者姓名未查到患者，显示添加弹窗
        DialogUtils.showDialogAddNewPatient(StoresalesActivity.this, R.string.wzdghz, new DialogListener() {
            @Override
            public void onCancl(Dialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onConfirm(Dialog dialog) {
                dialog.dismiss();
                showActivity(AddNewPatientAct.class, null);
            }
        }, R.string.cancel, R.string.xzhz);

    }

    @Override
    public void unPatientResult(int operater) {
        if(operater == 1){
            addNewPatient();
        }
    }

    @Override
    public void patientResult(ArrayList<Patient> patients, int operater) {
        if(operater ==1){
            showPatient(patients.get(0));
            onClick(tv_confim);
        }
    }

    private void addNewPatient() {
        //根据患者姓名未查到患者，显示添加弹窗
        DialogUtils.showDialogAddNewPatient(StoresalesActivity.this, R.string.wzdghz, new DialogListener() {
            @Override
            public void onCancl(Dialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onConfirm(Dialog dialog) {
                dialog.dismiss();
                Bundle bundle = new Bundle();
                MyClientBean myClientBean = new MyClientBean();
                myClientBean.setTruename(et_name.getText().toString().trim());
                myClientBean.setPhonenum(et_tel.getText().toString().trim());
                myClientBean.setCardtype(creditType);
                myClientBean.setIdcardnum(et_idcard.getText().toString().trim());
                if(hospitalBean != null) {
                    myClientBean.setHospitalid(hospitalid);
                    myClientBean.setHospitalname(hospitalBean.getHospitalname());
                }
                myClientBean.setDoctorname(et_jzys.getText().toString().trim());
                bundle.putSerializable("myClientBean", myClientBean);
                bundle.putInt("operaterType",0);
                showActivityForResult(AddNewPatientAct.class, bundle, Constants.REQUEST_ADD_PATIENT);

            }
        }, R.string.cancel, R.string.xzhz);

    }

    @Override
    public void addItem(int pos, DrugInfo info, int head_pos, DrugInfo headInfo) {
        LinearLayout itemView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.has_big_title_with_item, null);
        LinearLayout lin_item_head = (LinearLayout) itemView.findViewById(R.id.lin_item_head);
        TextView tv_yp_name = (TextView) itemView.findViewById(R.id.tv_yp_name);
        TextView tv_count = (TextView) itemView.findViewById(R.id.tv_count);
        TextView tv_ph = (TextView) itemView.findViewById(R.id.tv_ph);
        TextView tv_yxq = (TextView) itemView.findViewById(R.id.tv_yxq);
        TextView tv_bh = (TextView) itemView.findViewById(R.id.tv_bh);
        TextView tv_box = (TextView) itemView.findViewById(R.id.tv_box);

        View headView = lin_add.getChildAt(head_pos);
        if (headView != null) {
            TextView tv_count_head = (TextView) headView.findViewById(R.id.tv_count);
            tv_count_head.setText(headInfo.getCount() + "");
        } else {
            tv_count.setText(headInfo.getCount() + "");
        }

        tv_yxq.setText(info.getExpiredate());
        tv_bh.setText(info.getDrugcode());
        tv_box.setText(info.getQuantity() + "");
        tv_ph.setText(info.getBatchnumber());
        tv_yp_name.setText(headInfo.getDrugname());

        if (info.isFirst()) {
            lin_item_head.setVisibility(View.VISIBLE);
        } else
            lin_item_head.setVisibility(View.GONE);

        lin_add.addView(itemView, pos);
    }

    PhotoCallBack mPhotoCallBack = new PhotoCallBack() {
        @Override
        public void Success(final String path) {
            Log.i("fancl", "-----path" + path);
            //            img_fp.setImageBitmap(CameraUtil.fitSizeImg(path));
            //            new Thread(new Runnable() {
            //                @Override
            //                public void run() {
            //                    new PutAliyObject(MyApplication.oss, Constants.imgBucket, Utils.getOKey(), path, iHandler).asyncPutObjectFromLocalFile();
            //                }
            //            }).start();
            GetPhotoFromAlbum.compressImageByQuality(path, StoresalesActivity.this, iHandler);//压缩图片

        }

        @Override
        public void Failed(String errormsg) {
            showTelTip("失败" + errormsg);
        }
    };


    /**
     * 处理接收消息
     */
    private void addMessageHandler() {
        iHandler = new Handler() {
            public void handleMessage(Message msg) {
                try {
                    switch (msg.what) {
                        case Constants.UploadSuccess://阿里云上传图片成功
                            //                            Image img = (Image) msg.obj;
                            //                            //members.setHeadpicpath(img.getImagepath());
                            //
                            //                            if (icon == 1) {
                            //                                fpurl = img.getImagepath();
                            //                                img_fp.setImageBitmap(CameraUtil.fitSizeImg(localUrl));
                            //                            } else if (icon == 2) {
                            //                                cfurl = img.getImagepath();
                            //                                img_cf.setImageBitmap(CameraUtil.fitSizeImg(localUrl));
                            //                            }
                            Image img = (Image) msg.obj;
                            //members.setHeadpicpath(img.getImagepath());
                            if(currentClickType == REQUEST_CODE_CHOOSE) {
                                fpurl = img.getImagepath();
                                Log.i("swt", "fpurl = " + fpurl);
                                imgUrl.add(img.getImagepath());


                                if (imgUrl.size() == obtainPathResult.size()) {
                                    dialog.dismiss();
                                    storeAdapter.setData(imgUrl);
                                }
                            }else  if(currentClickType == REQUEST_CODE_CHOOSE_CF){
                                cfurl = img.getImagepath();
                                Log.i("swt", "cfurl = " + cfurl);
                                chuFangImgUrl.add(img.getImagepath());


                                if (chuFangImgUrl.size() == chuFangPathResult.size()) {
                                    dialog.dismiss();
                                    chuFangAdapter.setData(chuFangImgUrl);
                                }
                            }

                            break;

                        case Constants.UploadFailed://阿里云上传图片失败
                            //                            members.setHeadpicpath("");
                            if (icon == 1) {
                                fpurl = "";
                                img_fp.setImageResource(R.drawable.photograph_icon);
                            } else if (icon == 2) {
                                cfurl = "";
                                img_cf.setImageResource(R.drawable.photograph_icon);
                            }
                            dialog.dismiss();
                            showTip("上传图片失败");
                            break;
                        case 100://开始阿里云上传
                            if (icon == 1) {
                                fpurl = "";
                                img_fp.setImageResource(R.drawable.photograph_icon);
                            } else if (icon == 2) {
                                cfurl = "";
                                img_cf.setImageResource(R.drawable.photograph_icon);
                            }
                            //showTip("开始上传图片");
                            localUrl = (String) msg.obj;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    new PutAliyObject(MyApplication.oss, Constants.imgBucket, Utils.getOKey(), localUrl, iHandler).asyncPutObjectFromLocalFile();
                                }
                            }).start();
                            break;

                        default:

                            break;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("error.Root", e.toString());
                }
                super.handleMessage(msg);
            }
        };
    }


}
